package javaweb.dao.impl;

import javaweb.pojo.User;
import javaweb.utility.JDBCUnility;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author shkstart
 * @creat -07-13 19:33
 */
public abstract  class BaseDao {
private QueryRunner qr=new QueryRunner();
    public int upDate(String sql,Object...str){
    Connection conn = JDBCUnility.getConnection();
        try {
          return  qr.update(conn,sql,str);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
    public <T> T quryForOne(Class<T> type,String sql,Object...str){
        Connection conn = JDBCUnility.getConnection();
        try {
            return qr.query(conn,sql,new BeanHandler<T>(type),str);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
public <T> List<T> queryForList(Class<T> type,String sql,Object...str){
    Connection conn = JDBCUnility.getConnection();
    try {
        return qr.query(conn,sql,new BeanListHandler<T>(type),str);
    } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    }
public Object queryForSingValue(String sql,Object...str) {
    Connection conn = JDBCUnility.getConnection();
    try {
        try {
            return qr.query(conn, sql, new ScalarHandler(), str);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
        new RuntimeException(e);
    }
return null;
}
@Test
    public void Test01(){
    Connection conn = JDBCUnility.getConnection();
String sql="select * from user_book where username=?";
    try {
        User user1 = qr.query(conn, sql, new BeanHandler<>(User.class),
                "张杰");
        System.out.println(user1.getUsername());
        System.out.println(user1.getPassword());
    } catch (SQLException e) {
        e.printStackTrace();
    }

}


}
